package com.cloudkinto.service.wr.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.QuotationSchemeDao;
import com.cloudkinto.dao.WarehouseRentDao;
import com.cloudkinto.dao.WarehouseRentDetailDao;
import com.cloudkinto.entity.WarehouseRentDetailDo;
import com.cloudkinto.entity.WarehouseRentDo;
import com.cloudkinto.enumType.operate.OperateTypeEnum;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.wr.WarehouseRentService;
import com.cloudkinto.vo.ft.FreightStatusUpdateReq;
import com.cloudkinto.vo.wr.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hua
 * @since 2024-11-14
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class WarehouseRentServiceImpl extends ServiceImpl<WarehouseRentDao, WarehouseRentDo> implements WarehouseRentService {
    @Autowired
    private WarehouseRentDao dao;
    @Autowired
    private WarehouseRentDetailDao warehouseRentDetailDao;
    @Autowired
    private OperateRecordService operateRecordService;
    @Autowired
    private QuotationSchemeDao quotationSchemeDao;


    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    public void checkName(WhRentEt addReq, Long id, Long tenantId) {
        if (StringUtils.isBlank(addReq.getRuleName()))
            throw new BizException(SysConstant.Add_Name_Empty);
        //名称不能重复
        WarehouseRentDo et = dao.selectOne(new LambdaQueryWrapper<WarehouseRentDo>()
                .ne(id != null, WarehouseRentDo::getId, id)
                .eq(WarehouseRentDo::getRuleName, addReq.getRuleName())
                .eq(WarehouseRentDo::getTenantId, tenantId).last(" order by id desc limit 1"));
        if (et != null) throw new BizException(SysConstant.Add_Name_Same);
    }

    @Override
    public Object add(WhRentAddReq req, Long userId, Long tenantId) {
        this.checkName(req, null, tenantId);
        WarehouseRentDo entityDo = new WarehouseRentDo();
        BeanUtils.copyProperties(req, entityDo);
        dao.insert(entityDo);
        for (WhRentDetailEt whRentDetailEt : req.getList()) {
            WarehouseRentDetailDo detailDo = new WarehouseRentDetailDo();
            BeanUtils.copyProperties(whRentDetailEt, detailDo);
            detailDo.setRentId(entityDo.getId());
            warehouseRentDetailDao.insert(detailDo);
        }
        operateRecordService.operateAddRecordAndValue("新建仓租费", "", entityDo.getId(), userId, null, OperateTypeEnum.WHRent);
        return entityDo.getId();
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(WhRentUpdateReq req, Long userId, Long tenantId) {
        WarehouseRentDo entityDo = dao.selectById(req.getId());
        //判断仓租费有没有被使用过
        int qsItemTypeUseCount = quotationSchemeDao.getQsItemTypeUseCount(req.getId(), 2, tenantId);
        if (qsItemTypeUseCount > 0) {
            if (!Objects.equals(req.getCurrencyCode(), entityDo.getCurrencyCode()))
                throw new BizException(SysConstant.WhRent_CurrencyCode_CannotEdit);
            req.setRuleName(entityDo.getRuleName());
        }
        this.checkName(req, req.getId(), tenantId);
        BeanUtils.copyProperties(req, entityDo);
        dao.updateById(entityDo);
        List<WarehouseRentDetailDo> rentDetailDoList = warehouseRentDetailDao.selectList(new LambdaQueryWrapper<WarehouseRentDetailDo>()
                .eq(WarehouseRentDetailDo::getRentId, entityDo.getId()));
        List<Long> oldIds = rentDetailDoList.stream().map(WarehouseRentDetailDo::getId).collect(Collectors.toList());
        List<Long> newIds = req.getList().stream().map(WhRentDetailUpdateReq::getId).filter(Objects::nonNull).collect(Collectors.toList());
        List<Long> deleteIds = oldIds.stream().filter(i -> !newIds.contains(i)).collect(Collectors.toList());
        if (!deleteIds.isEmpty()) warehouseRentDetailDao.updateDelete(deleteIds, userId);
        for (WhRentDetailUpdateReq detailUpdateReq : req.getList()) {
            if (detailUpdateReq.getId() != null && !detailUpdateReq.isEdit()) continue; //id存在 且没修改过
            WarehouseRentDetailDo detailDo = new WarehouseRentDetailDo();
            BeanUtils.copyProperties(detailUpdateReq, detailDo);
            if (detailUpdateReq.getId() == null) {
                detailDo.setRentId(entityDo.getId());
                warehouseRentDetailDao.insert(detailDo);
            } else {
                //修改
                warehouseRentDetailDao.updateById(detailDo);
            }
        }
        operateRecordService.operateAddRecordAndValue("更新仓租费", "", entityDo.getId(), userId, null, OperateTypeEnum.WHRent);
        return entityDo.getId();
    }


    @Override
    public int delete(Long id, Long userId, Long tenantId) {
        WarehouseRentDo entityDo = dao.selectById(id);
        if (entityDo == null) return 0;
        if (!Objects.equals(entityDo.getTenantId(), tenantId)) return 0;
        int qsItemTypeUseCount = quotationSchemeDao.getQsItemTypeUseCount(id, 2, tenantId);
        if (qsItemTypeUseCount > 0) throw new BizException(SysConstant.WarehouseRent_Related_CannotEdit);
        int i = dao.updateDelete(id, userId);
        if (i > 0) warehouseRentDetailDao.updateDeleteByRentId(id, userId);
        return i;
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(WarehouseRentDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public WhRentInfoRes detail(Long id, Long tenantId) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("tenantId", tenantId);
        List<WhRentPageVo> list = dao.list(map);
        if (list.isEmpty()) return null;
        WhRentInfoRes res = new WhRentInfoRes();
        BeanUtils.copyProperties(list.get(0), res);
        List<WarehouseRentDetailDo> rentDetailDoList = warehouseRentDetailDao.selectList(new LambdaQueryWrapper<WarehouseRentDetailDo>()
                .eq(WarehouseRentDetailDo::getRentId, id));
        List<WhRentDetailInfoRes> detailList = JSONUtil.toList(JSONUtil.toJsonStr(rentDetailDoList), WhRentDetailInfoRes.class);
        detailList.sort((o1, o2) -> {
            if (o1.getStartAge() == 0 && o1.getEndAge() == 0) {
                return 1;
            } else if (o2.getStartAge() == 0 && o2.getEndAge() == 0) {
                return -1;
            } else {
                return Integer.compare(o1.getStartAge(), o2.getStartAge());
            }
        });
        res.setList(detailList);
        res.setOperateResList(operateRecordService.getOperateList(id, OperateTypeEnum.WHRent));
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        Map<String, Object> result = new HashMap<>();
        result.put("fullOneCarryBit", StaticDict.getWh_Rent_FullOneCarryBit());
        return SingleResult.success(result);
    }

    @Override
    public List<WhRentPageVo> getList(Map<String, Object> map) {
        return dao.list(map);
    }

    @Override
    public PageResult getListPage(Map<String, Object> map) {
        IPage<WhRentPageVo> page = pageInitDto(map);
        page = dao.list(page, map);
        PageResult result = new PageResult(page.getRecords(), (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<Object> handlerListAfter(List<WarehouseRentDo> list) {
        List<Object> result = new ArrayList<>();
        return result;
    }

    private IPage<WarehouseRentDo> pageInit(Map<String, String> map) {
        IPage<WarehouseRentDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private IPage<WhRentPageVo> pageInitDto(Map<String, Object> map) {
        IPage<WhRentPageVo> page = new Page();
        page.setSize(map.get("pageSize") != null ? Long.parseLong(map.get("pageSize").toString()) : 10);
        page.setCurrent(map.get("current") != null ? Long.parseLong(map.get("current").toString()) : 1);
        return page;
    }


    private QueryWrapper<WarehouseRentDo> queryBuild(Map<String, String> map) {
        QueryWrapper<WarehouseRentDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }

    @Override
    public void updateStatus(FreightStatusUpdateReq req, Long userId, Long tenantId) {
        WarehouseRentDo et = dao.selectById(req.getId());
        if (et == null) return;
        if (et.getStatus() == req.getStatus()) return;
        if (!Objects.equals(et.getTenantId(), tenantId)) return;
        int qsItemTypeUseCount = quotationSchemeDao.getQsItemTypeUseCount(et.getId(), 2, tenantId);
        if (qsItemTypeUseCount > 0) throw new BizException(SysConstant.WarehouseRent_Related_CannotEdit);
        et.setStatus(req.getStatus());
        dao.updateById(et);
        operateRecordService.operateAddRecordAndValue(req.getStatus() == 0 ? "启动仓租费" : "停用仓租费", "", et.getId(), userId, null, OperateTypeEnum.WHRent);
    }


}
